// middleware/errorHandler.ts
import { Request, Response, NextFunction } from 'express';
import { ResponseUtil } from '@/utils/R';
import logger from '@/utils/logger';

export interface CustomError extends Error {
    status?: number;
    code?: number;
}

const errorHandler = (
    err: CustomError,
    req: Request,
    res: Response,
    next: NextFunction
) => {
    // 如果响应已经发送，直接返回
    if (res.headersSent) {
        return next(err);
    }

    // 记录错误日志
    logger.error(`[${new Date().toISOString()}] Error: message: ${err.message}, stack: ${err.stack}, url: ${req.url}, method: ${req.method}, ip: ${req.ip}`);

    // 根据错误类型返回不同的响应
    switch (err.status || err.code) {
        case 400:
            return ResponseUtil.badRequest(res, err.message);
        case 401:
            return ResponseUtil.unauthorized(res, err.message);
        case 403:
            return ResponseUtil.forbidden(res, err.message);
        case 404:
            return ResponseUtil.notFound(res, err.message);
        default:
            // 生产环境不返回具体错误信息
            const message = process.env.NODE_ENV === 'production'
                ? '服务器内部错误'
                : err.message;
            return ResponseUtil.internalError(res, message);
    }
};


export default errorHandler;